import ala from '@/service/ala'
import api from '@/service/api'
const baseConfig = require('@/service/ala/base')
var {
  projectId,
  privateKey
} = baseConfig.baseConfig()

/*
 * 构建头部信息，共8个参数
 * 计算每个请求的token，不同的接口，不同的时间，请求token都不一样
 */
export function header(apiUrl, isDiy) {
  var filter = ala.filter()
  var base = baseToken(apiUrl)
  var site = api.site()
  var headObj = {
    'Timestamp': base.timestamp,
    'Token': base.token,
    'Tenant': ala.tenant(),
    'Filter': filter,
    'Accept-ExpireTime': base.expireTime,
    'User-Token': base.userToken,
    'User-Identity': base.userId,
    'Accept-Project': projectId,
    'Client-Url': base.apiUrl,
    'Accept-Sign': base.sign
  }
  // 供应商信息
  if (filter === 11) {
    var userType = api.userType()
    if (!userType) {
      ala.push('/admin-store/login')
      return headObj
    }
    headObj = {
      ...headObj,
      'Accept-UserType-Identity': userType.id,
      'Accept-UserType-Token': tokenUserType(userType, base.timestamp, site)
    }
  }
  // diy传输的头部信息
  if (isDiy === true) {
    if (!site) {
      return headObj
    }
    headObj = {
      ...headObj,
      'Accept-Site-Token': tokenDiyHeader(site, apiUrl),
      'Accept-Site-Identity': site.id
    }
  }
  return headObj
}


/*
 * 头部传入token机制,算法和后台匹配，管理员可以在后台随时修改
 * 对应zk-token
 */
function baseToken(apiUrl) {
  apiUrl = tokenApiUrl(apiUrl)
  var timestamp = ala.timestamp()
  var sign = `${apiUrl}-${projectId}-${ala.tenant()}-${privateKey}-${timestamp}`
  var token = ala.md5(sign.toLowerCase())
  var result = {
    token: token,
    sign: sign,
    apiUrl: apiUrl,
    timestamp: timestamp
  }
  // 用户相关token
  var userOutputToken = ala.userToken()
  if (userOutputToken) {
    var userToken = token.substring(2, 12) + userOutputToken.token
    result.userToken = ala.md5(userToken.toLowerCase())
    result.expireTime = userOutputToken.expireTime
    result.userId = userOutputToken.userId
  }
  return result
}

/*
 * diy页面请求时候的token
 */

function tokenDiyHeader(site, apiUrl) {
  var token = apiUrl + '-' + ala.timestamp() + '-' + site.id + '-' + site.userId
  token = ala.md5(token.toLowerCase())
  return token
}


/**
 * 供应商店铺的token
 */
function tokenUserType(userType, timestamp, site) {
  var token = userType.id + '-' + timestamp + '-' + site.id + '-' + userType.userId
  token = ala.md5(token.toLowerCase())
  return token
}
/*
 * 规范加密ApiUrl
 */
function tokenApiUrl(apiUrl) {
  var index = apiUrl.indexOf('?')
  if (index > 0) {
    apiUrl = apiUrl.substring(0, index)
  }
  apiUrl = apiUrl.toLowerCase().replace('//', '/')
  return apiUrl
}
